// 缓存工具函数
import Keys from './constant/keys'

// 获取token
export const getToken = ( ) => {
    return getCache(Keys.tokenKey,'s')
}

// 存储token
export const setToken = (token:string) => {
    setCache(Keys.tokenKey,token,'s')
}

/**
   *  @description 获取缓存
   * @param key 索引值
   * @param type 缓存类型 [l|s], l: localStorage  s: sessionStorage 默认 l
   * @returns
   */
export const getCache = (key: string, type: 'l' | 's' = 'l'): any => {
    let data: string | null;
    data = type === 'l' ? localStorage.getItem(key) : sessionStorage.getItem(key)
    try {
        return JSON.parse(data as string);
    } catch (err) {
        return data;
    }
}

/**
 * @description 设置缓存
 * @param key 索引值
 * @param value 缓存内容
 * @param type 缓存类型 [l|s], l: localStorage  s: sessionStorage 默认 l
 */
 export const setCache = (key: string, value: string | Array<any> | boolean, type: 'l' | 's' = 'l'): void => {
    if (type === 'l') {
        localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
    } else {
        sessionStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
    }
}